import {useState, useRef, useEffect} from 'react'
import { useSearchParams } from 'react-router-dom'
import ReactJsMind, { IDataItem, IData } from 'react-jsmind'
import {IRecently, recentlyAdd, recentlyConfig, recentlyEdit, recentlyView, recently} from '@/api/recently.ts'
import useConfigDataFile from "@/hooks/useConfigDataFile.ts";
import 'react-jsmind/dist/index.min.css'
import {Button, Flex, Form, Input, message} from "antd";
import { useNavigate } from 'react-router-dom'
import RecentlyModal from "@/components/recently/RecentlyModal.tsx";
import useDomToImage from "@/hooks/useDomToImage.ts";

interface IMindRef {
    getData: () => IData
}

interface IRecentlyRefProps {
    showModal: () => void
    handleCancel: () => void
    handleOk: () => void
}

const AddRecently = () => {
    const [form] = Form.useForm()
    const mindRef = useRef(null)
    const mindDivRef = useRef(null)
    const { dataFile } = useConfigDataFile('')
    const recentlyModalRef = useRef(null)
    const { domImage } = useDomToImage(mindDivRef)
    const [searchParams] = useSearchParams()
    const navigate = useNavigate()
    const [initialValues, setInitialValues] = useState<{ name: string, describe: string }>({ name: '', describe: '' })
    // const [name, setName] = useState('')
    // const [describe, setDescribe] = useState('')
    const [NodeTreeData, setNodeTreeData] = useState<IData>({
        meta: { name: 'mind图', author: 'Your Name', version: '0.8.5' },
        format: 'node_tree',
        data: {
            id: 'root',
            topic: '根节点',
            children: [{
                id: "1",
                topic: "子节点1",
                expanded: true,
                direction: "left",
                "background-color": "#03BF8A",
                data: {
                    width: 100,
                    type: "rect"
                }
            }],
        },
    })
    const [editable, setEditable] = useState(true)
    const getData = async () => {
        if (recentlyModalRef.current) {
            (recentlyModalRef.current as IRecentlyRefProps).showModal()
        }
    }
    const getDataApi = () => {
        recentlyConfig(searchParams.get('path') as string).then(data => {
            setNodeTreeData(data)
        })
    }
    const getView = () => {
        recentlyView({ path: searchParams.get('path') as string }).then(res => {
            if (res.code === 200) {
                const data: IRecently = res.data[0]
                setInitialValues({ name: data.name, describe: data.describe })
                form.setFieldsValue({ name: data.name, describe: data.describe })
            }
        })
    }
    useEffect(() => {
        if (searchParams.get('path')) {
            getDataApi()
            getView()
        }
    }, []);

    const enableEdit = () => {
        setEditable(!editable)
    }
    const onNodeClick = (node: IDataItem) => {
        console.log('点击的节点', node)
    }
    const finish = async (values: { name: string, describe: string }) => {
        if (mindRef.current) {
            const data = (mindRef.current as IMindRef).getData()
            const file = dataFile(JSON.stringify(data), searchParams.get('path') as string)
            const formData = new FormData
            formData.append('file', file)
            if (searchParams.get('path')) {
                formData.append('path', searchParams.get('path') as string)
                formData.append('name', values.name)
                formData.append('describe', values.describe)
                await recentlyEdit(formData)
                handleCancel()
            } else {
                const data = await recently(formData)
                await recentlyAdd({ name: values.name, describe: values.describe, fileURL: data.data.fileURL })
                navigate('/recently/list')
            }
            message.success('上传成功')
        }
    }
    const handleCancel = () => {
        if (recentlyModalRef.current) {
            (recentlyModalRef.current as IRecentlyRefProps).handleCancel()
        }
    }
    return (
        <div style={{width: '100%', height: '100%', background: '#fff', borderRadius: '5px'}}>
            <div style={{ height: '42px', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'end', padding: '10px', boxSizing: 'border-box' }}>
                <Flex gap='middle' wrap justify='end'>
                    <RecentlyModal ref={recentlyModalRef} content={
                        <Form form={form} onFinish={finish} initialValues={initialValues}>
                            <Form.Item label='标题' name='name'>
                                <Input />
                            </Form.Item>
                            <Form.Item label='备注' name='describe'>
                                <Input.TextArea />
                            </Form.Item>
                            <Form.Item>
                                <Flex gap='middle' wrap justify='end'>
                                    <Button onClick={handleCancel}>取消</Button>
                                    <Button type='primary' htmlType="submit">确定</Button>
                                </Flex>
                            </Form.Item>
                        </Form>
                    } btn={<Button onClick={getData} type='link'>上传</Button>} />
                    <Button onClick={domImage} type='link'>下载图片</Button>
                    <Button type='link' danger={editable} onClick={enableEdit}>{editable ? '关闭' : '开启'}编辑</Button>
                </Flex>
            </div>
            <div ref={mindDivRef} style={{height: 'calc(100% - 42px)'}}>
                <ReactJsMind ref={mindRef} options={{editable}} data={NodeTreeData} onClick={onNodeClick}/>
            </div>

        </div>
    )
}

export default AddRecently